package com.bbx.taxi.client.pay.alipay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.alipay.sdk.app.PayTask;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.passanger.PayBuild;
import com.bbx.api.sdk.model.passanger.Token;
import com.bbx.api.sdk.model.passanger.Return.pay.Pay;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.CodeNet;
import com.bbx.api.sdk.net.passeger.conn.pay.PayNet;
import com.bbx.api.util.LogUtils;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Order.OrderEvaluationActivity2;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.taxi.client.Task.MyOrderPayTask;
import com.bbx.taxi.client.Util.AppStarted;
import com.bbx.taxi.client.Util.VersionUtils;
import com.bbx.taxi.client.Util.VersionUtils.VersionType;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

public class PayAlipay {
	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;

	public Activity mContext;

	public String order_id;

	public String driver_id;

	AlipayTask mAlipayTask;

//	// 支付宝支付完成接口
//	public interface OnAliPayFinishListener {
//		public void onAliPayFinish(boolean isSuccess);
//	}
//
//	public static OnAliPayFinishListener mOnAliPayFinishListener = null;
//
//	public static void setOnAliPayFinishListener(OnAliPayFinishListener l) {
//		mOnAliPayFinishListener = l;
//	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);

				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();

				String resultStatus = payResult.getResultStatus();
				LogUtils.e("", "resultStatus:" + resultStatus);
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
					if(MyOrderPayTask.mOnPayFinishListener!=null)MyOrderPayTask.mOnPayFinishListener.onPayFinish(true);
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(mContext, "支付结果确认中", Toast.LENGTH_SHORT)
								.show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT)
								.show();
						if(MyOrderPayTask.mOnPayFinishListener!=null)MyOrderPayTask.mOnPayFinishListener.onPayFinish(false);

					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(mContext, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT)
						.show();
				break;
			}
			default:
				break;
			}
		};
	};

	public PayAlipay(Activity context, String order_id, String driver_id) {
		this.mContext = context;
		this.order_id = order_id;
		this.driver_id = driver_id;
	}
	public PayAlipay(Activity context) {
		this.mContext = context;
	}

//	/**
//	 * 订单支付
//	 * 传入的价钱请以10.00元格式传入。。。 价钱,微信是以分为单位，支付是以元为单位，所以微信为整形，支付为double，注意检查
//	 */
//	public void pay() {
//		MyApplication myApplication = MyApplication.getInstance();
//		// 访问服务器获取支付订单
//		PayBuild mPayBuild = new PayBuild(mContext);
//		mPayBuild.uid = myApplication.getUid();
//		mPayBuild.access_token = myApplication.getToken();
//		mPayBuild.order_id = order_id;
//		mPayBuild.orderType = "1";
//		switch(VersionUtils.getVersionType(mContext)){
//		case bbx:
//			mPayBuild.gateway="alipay";
//			break;
//		case tianshang:
//			mPayBuild.gateway="alipay_ts";
//			break;
//		}
//		mPayBuild.cashAmt = "0.01";
//		mPayBuild.driver_id = driver_id;
//		mAlipayTask = new AlipayTask(mContext, mPayBuild);
//		mAlipayTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//	}

	// 访问服务器获取支付订单
	// //////////////////////////////////////////////////
	public class AlipayTask extends BaseAsyncTask {
		PayBuild mPayBuild;

		public AlipayTask(Activity context, PayBuild mPayBuild) {
			super(context);
			this.mPayBuild = mPayBuild;
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mPayBuild).getJson();
			return new PayNet(context, json);
		}

		@Override
		public void onSuccess(int status,Object object) {
			if (object != null) {
				Pay mPay = (Pay) object;
				// 完整的符合支付宝参数规范的订单信息
				// final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				// + getSignType();
				// final String payInfo
				// ="partner=\"2088811107821456\"&seller_id=\"herewegozfb@yeah.net\"&out_trade_no=\"1124140723-1733\"&subject=\"测试的商品\"&body=\"该测试商品的详细描述\"&total_fee=\"0.01\"&notify_url=\"http://notify.msp.hk/notify.htm\"&service=\"mobile.securitypay.pay\"&payment_type=\"1\"&_input_charset=\"utf-8\"&it_b_pay=\"30m\"&return_url=\"m.alipay.com\"&sign=\"t5DDP8SOUaz8galyvVfyx6gv%2B1NPZma4zDl34t5j7AN1Gef49U0Crzq3dy%2BTp9RS%2BmsEBjQof2A4RSYZRyQW8Olw8AGmWraM4MdKvIxaReNrUT2g8ZVjSnvjvfmubTkPFSHDfuYxO8WJYu8LEpyFcymA7ctZmKmqN39ijp9%2FVa8%3D\"&sign_type=\"RSA\"";
				// final String
				// payInfo="input_charset=\"utf-8\"&body=\"BBX SERVER\"&it_b_pay=\"30m\"&notify_url=\"http://110.87.111.3:8060/bbxpaymanage-web/notify/alipay\"&out_trade_no=\"I20151124160346B7029\"&partner=\"2088021403011402\"&payment_type=\"1\"&seller_id=\"zfb@bbxpc.com\"&service=\"mobile.securitypay.pay\"&sign=\"N3gjuikVkbJiJEiqzPtyMWHRjkxV7OkO2oCdygrvlVpVdtGIoV2M7xv5gHBrleNIngS5vCo6SkJ9AiKgt11FvWeLtH/cZb/lUMxyiitKbX/N8Q8/90eDxjMNE5UEhuXcD2roHtWo5Da5p5rq9seKIRv75tmrapqWIj70kiJTLGQ=\"&sign_type=\"RSA\"&subject=\"BBX SERVER\"&total_fee=\"0.01\"";
				Pay.Detail detail = mPay.getDetail();
				//0元则需要线下支付
				if (detail != null && detail.geteWay() != null
						&& detail.geteWay().equals("line")) {
					if(MyOrderPayTask.mOnPayFinishListener!=null)MyOrderPayTask.mOnPayFinishListener.onPayFinish(true);
				} else {
					if (detail != null && detail.getSign() != null
							&& detail.getData() != null
							&& detail.getSign_type() != null) {
						// 对订单做RSA 签名
						String sign = detail.getSign();
						try {
							// 仅需对sign 做URL编码
							sign = URLEncoder.encode(sign, "UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
						// 完整的符合支付宝参数规范的订单信息
						final String payInfo = detail.getData() + "&sign=\""
								+ sign + "\"&" + "sign_type=\""
								+ detail.getSign_type() + "\"";
						LogUtils.e("", "payInfo:" + payInfo);
						Runnable payRunnable = new Runnable() {

							@Override
							public void run() {
								// 构造PayTask 对象
								PayTask alipay = new PayTask(mContext);
								// 调用支付接口，获取支付结果
								String result = alipay.pay(payInfo);

								Message msg = new Message();
								msg.what = SDK_PAY_FLAG;
								msg.obj = result;
								mHandler.sendMessage(msg);
							}
						};

						// 必须异步调用
						Thread payThread = new Thread(payRunnable);
						payThread.start();
					} else {
						ToastUtil.showToast(context, R.string.no_network);
					}
				}
			} else {
				ToastUtil.showToast(context, R.string.no_network);
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			// TODO Auto-generated method stub
			ToastUtil.showToast(context, R.string.no_network);
		}
	}

	/**
	 * @param sign
	 * @param sign_type
	 * @param data
	 * 订单支付
	 */
	public void onPay(String sign,String sign_type,final String data){
		onRecharge(sign,sign_type,data);
	}
	/**账号充值*/
	public  void  onRecharge(String sign,String sign_type,final String data){
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = data + "&sign=\""
				+ sign + "\"&" + "sign_type=\""
				+ sign_type + "\"";
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(mContext);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};
		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}
}
